<script setup>
import {
  ElTable,
  ElTableColumn,
  ElImage,
  ElDrawer,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelectV2,
  ElUpload,
  ElIcon
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import SingleButton from '@/components/SingleButton.vue'
import { ref, reactive, computed } from 'vue'
import showPrompt from '@/utils/showPrompt'
import { useGoodsStore } from '@/stores'

const goodsStore = useGoodsStore()
const goodsText = ref('商品添加')

const allTypesObject = goodsStore.typesList.map(item => ({
  value: item.type,
  label: item.type
}))

const typesObject = goodsStore.typesList
  .filter(item => item.type !== '全部')
  .map(item => ({
    value: item.type,
    label: item.type
  }))

const goodsList = ref(goodsStore.goodsList)

const filterList = computed(() => {
  const result = goodsList.value.filter(item => item.type === chosenType.value)
  if (result.length) {
    return result
  } else if (chosenType.value === '全部') {
    return goodsList.value
  } else {
    return result
  }
})

const chosenType = ref('全部')

const drawer = ref(false)
const goodsInfo = ref({
  id: '',
  name: '',
  price: '',
  desc: '',
  imgUrl: '',
  type: ''
})

function findGoodsFromId(id) {
  const result = goodsList.value.find(item => item.id === id)
  return result
}

const tempName = ref('')
const tempPrice = ref(null)
const tempDesc = ref('')
const tempImgUrl = ref('')
const tempType = ref('')
const type = ref('')

const add = () => {
  drawer.value = true
  goodsInfo.value = {}
  type.value = 'add'
  goodsText.value = '商品添加'
}

const edit = id => {
  drawer.value = true
  type.value = 'edit'
  goodsText.value = '商品编辑'
  if (id) {
    const result = findGoodsFromId(id)
    goodsInfo.value = result
    tempName.value = goodsInfo.value.name
    tempPrice.value = goodsInfo.value.price
    tempDesc.value = goodsInfo.value.desc
    tempType.value = goodsInfo.value.type
    tempImgUrl.value = goodsInfo.value.imgUrl
  }
}

const del = id => {
  if (id) {
    goodsList.value = goodsList.value.filter(item => item.id !== id)
    goodsStore.delGoods(id)
  }
  showPrompt('删除成功', 'success')
}

const cancel = () => {
  drawer.value = false
  if (type.value === 'add') return
  goodsInfo.value.name = tempName.value
  goodsInfo.value.price = tempPrice.value
  goodsInfo.value.desc = tempDesc.value
  goodsInfo.value.type = tempType.value
  goodsInfo.value.imgUrl = tempImgUrl.value
}

const save = () => {
  if (type.value === 'add') {
    goodsStore.addGoods(goodsInfo.value)
    showPrompt('添加成功', 'success')
  } else if (type.value === 'edit') {
    goodsStore.modifyGoods()
    showPrompt('保存成功', 'success')
  } else {
    console.error('type 未定义')
  }
  drawer.value = false
  type.value = ''
}

const ruleFormRef = ref()

const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度必须在1-30', trigger: 'blur' }
  ],
  price: [
    {
      required: true,
      message: '请输入商品价格',
      trigger: 'change'
    },
    { validator: isValidPrice, message: '请输入正确的数字', trigger: 'blur' }
  ],
  desc: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 1, max: 100, message: '长度必须在1-100', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择商品类型' }],
  imgUrl: [{ required: true, message: '请选择商品图片' }]
})

function isValidPrice(_, value) {
  const regex = /^\d*\.?\d+$/
  return regex.test(value)
}

function beforeAvatarUpload(file) {
  const isImage = file.type.startsWith('image/')

  if (!isImage) {
    showPrompt('非图片类型', 'error')
  }

  return isImage
}

function customUpload(option) {
  const file = option.file
  const reader = new FileReader()

  reader.onload = e => {
    goodsInfo.value.imgUrl = e.target.result
  }

  reader.readAsDataURL(file)
}
</script>

<template>
  <h2>商品管理</h2>
  <div class="goods">
    <el-select-v2
      style="width: 300px; margin-bottom: 20px"
      v-model="chosenType"
      placeholder="请选择商品类型"
      :options="allTypesObject"
    />
    <SingleButton @click="add('add')" class="btn" text="添加商品" />
  </div>
  <el-table class="goods-table" :data="filterList" style="width: 100%; height: calc(100vh - 260px)">
    <el-table-column prop="id" label="ID" width="100" />
    <el-table-column prop="name" label="商品名称" width="150" />
    <el-table-column prop="price" label="价格" width="100" />
    <el-table-column prop="desc" label="商品描述" width="400" />
    <el-table-column prop="type" label="商品类型" width="100" />
    <el-table-column label="商品图片" width="150">
      <template #default="scope">
        <el-image class="el-img" :src="scope.row.imgUrl" />
      </template>
    </el-table-column>
    <el-table-column class="operation" fixed="right" label="操作" width="300">
      <template #default="item">
        <div class="operation">
          <SingleButton text="编辑" @click="edit(item.row.id, 'edit')" />
          <SingleButton text="删除" @click="del(item.row.id)" />
        </div>
      </template>
    </el-table-column>
  </el-table>
  <el-drawer
    v-model="drawer"
    direction="rtl"
    size="100%"
    style="max-width: 600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    :show-close="false"
  >
    <template #header>
      <h4>{{ goodsText }}</h4>
    </template>
    <template #default>
      <br /><br />
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="goodsInfo"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="goodsInfo.name" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="goodsInfo.price" />
        </el-form-item>
        <el-form-item label="商品描述" prop="desc">
          <el-input v-model="goodsInfo.desc" type="textarea" />
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-select-v2
            v-model="goodsInfo.type"
            placeholder="请选择商品类型"
            :options="typesObject"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="imgUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="customUpload"
            :before-upload="beforeAvatarUpload"
          >
            <img
              width="178"
              height="178"
              v-if="goodsInfo.imgUrl"
              :src="goodsInfo.imgUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <div class="operation">
          <SingleButton style="margin-left: auto" text="取消" @click="cancel" />
          <SingleButton text="保存" @click="save" />
        </div>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
h2 {
  margin-bottom: 40px;
}

.goods {
  display: flex;

  .btn {
    height: 32px;
    margin-left: 20px;
    font-size: 14px;
  }
}

:deep(.el-img) {
  img {
    width: 100px;
    height: 100px;
  }
}

.operation {
  display: flex;
  gap: 10px;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
